package com.company.bookstore.aspect;

import com.company.bookstore.common.redis.RedisUtil;
import com.company.bookstore.common.result.MvcResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * ip 与多层代理
 * https://blog.csdn.net/tanyit/article/details/6925317
 * 自定义注解
 * https://blog.csdn.net/xsp_happyboy/article/details/80987484
 * redisson实现分布式限流
 * https://blog.csdn.net/weixin_34306593/article/details/92645619
 * Aop
 * https://blog.csdn.net/u012326462/article/details/82529835?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
 * */
@Aspect
@Component
@Slf4j
public class ConstraintIpAndMethod  {

    @Resource
    RedisUtil redisUtil;
   /**
    *     @ Around环绕通知
    *  : @Before通知执行
    *  : @Before通知执行结束
    *  : @Around环绕通知执行结束
    *  : @After后置通知执行了!
    *  : @AfterReturning第一个后置返回通知的返回值：18
    *
    * */
    @Around(value = "@annotation(com.company.bookstore.aspect.CIAM)")
    public Object  isValid(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("enter aop isValid method");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        String key = method.getAnnotation(CIAM.class).methodName();
        log.info("limit key is : {}",key);
        Object result ;
        if (LimitRateFactory.containKey(key)){
            if (LimitRateFactory.invoke(key)){
                result = joinPoint.proceed();
            }else {
                result = MvcResult.INTERFACE_LIMIT;
            }
        }else {
            LimitRateFactory.register(key,redisUtil.createOrResetInterfaceLimitMap(key));
            result = joinPoint.proceed();
        }
//        result = MvcResult.LOGING_ERROR;
        return result;
    }
    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if(ip.contains(",")){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
       log.info("ConstraintIpAndMethod ===> acquire client ip: {}" , ip);
        return ip;
    }


}
